package com.lg.atp.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.lg.atp.dao.AttachmentDao;
import com.lg.atp.dao.ControlDao;
import com.lg.atp.dao.NumberInfoDao;
import com.lg.atp.entity.TblAttachment;
import com.lg.atp.entity.TblControls;
import com.lg.atp.entity.TblNumberInfo;
import com.lg.atp.sercurity.SecurityUserHolder;
import com.lg.atp.service.IControlService;
import com.lg.atp.utils.PictureTool;

@Service("iControlService")
public class ControlServiceImpl implements IControlService{

	@Autowired
	private ControlDao controlDao;
	@Autowired
	private NumberInfoDao numberInfoDao;
	
	@Autowired
	private AttachmentDao attachmentDao;
	
	private @Value("${targetFilePath}") String targetFilePath;
	private final static String numberCode = "CONTROLS";
	
	//日期+数据库中保存数据+3位随机数
	@Override
	public String generateNewCode() {
		
		String date = DateFormatUtils.format(new Date(), "yyyyMMdd");
		TblNumberInfo number = new TblNumberInfo();
		number.setNumberCode(numberCode);
		number.setPrefixCode(date);
		Long maxNum = numberInfoDao.selectMaxNum(number);
		if(maxNum == null){
			number.setCurrentNumber(1l);
			numberInfoDao.saveNum(number);
			int randomInt =(int)(Math.random()*1000);
			return date+1+String.format("%03d", randomInt);
		}else{
			Long newNum = maxNum+1;
			number.setCurrentNumber(newNum);
			numberInfoDao.updateNum(number);
			int randomInt =(int)(Math.random()*1000);
			return date+newNum+String.format("%03d", randomInt);
		}
	}
	
	@Transactional
	@Override
	public TblControls saveControl(TblControls control) {
		//String controlNumber = this.generateNewCode();
		//control.setControlNumber(controlNumber);
		if (control.getControlLocationType()==3) {
			String imgName = UUID.randomUUID()+".jpg";
			String sourceFilePath = "img/control/"+imgName;
			PictureTool.GenerateImage(control.getPictrueBase(), targetFilePath+sourceFilePath);
			TblAttachment attachment = new TblAttachment();
			attachment.setCreateTime(new Timestamp(new Date().getTime()));
			attachment.setFilePath(sourceFilePath);
			attachment.setCreateUserId(SecurityUserHolder.getCurrentUser().getId());
			attachment.setFileNameNew(imgName);
			attachment.setFileNameOld(imgName);
			attachment.setFileType("jpg");
			attachmentDao.saveFile(attachment);
			control.setControlImageAttachmentId(attachment.getId());
		}
		controlDao.saveControl(control);
		return control;
	}
	@Override
	public List<TblControls> updateControl(TblControls control) {
		if (control.getControlLocationType()==3) {
			TblControls control2 = controlDao.selectControlById(control.getId());
			String afterBase64="";
			if(control2.getControlImageAttachmentId()!=null){
				
				TblAttachment attachment1 = attachmentDao.selectFileById(control2.getControlImageAttachmentId());
				String tagetFile = targetFilePath+attachment1.getFilePath();
				afterBase64 = (attachment1==null || attachment1.getFilePath()==null)?"":PictureTool.GetImageStr(tagetFile);
				
			}
			if(!control.getPictrueBase().equals(afterBase64)){
				String imgName = UUID.randomUUID()+".jpg";
				String sourceFilePath = "img/control/"+imgName;
				PictureTool.GenerateImage(control.getPictrueBase(), targetFilePath+sourceFilePath);
				TblAttachment attachment = new TblAttachment();
				attachment.setCreateTime(new Timestamp(new Date().getTime()));
				attachment.setFilePath(sourceFilePath);
				attachment.setCreateUserId(SecurityUserHolder.getCurrentUser().getId());
				attachment.setFileNameNew(imgName);
				attachment.setFileNameOld(imgName);
				attachment.setFileType("jpg");
				attachmentDao.saveFile(attachment);
				control.setControlImageAttachmentId(attachment.getId());
			}else{
				control.setScreenHeight(control2.getScreenHeight());
			}
		}
		controlDao.updateControl(control);
		return this.selectControlWithChildById(control.getId());
	}
	@Override
	public void delControl(Long id) {
		TblControls control = controlDao.selectControlById(id);
		String parentIds = control.getParentIds() == null?""+id:control.getParentIds()+","+id;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("parentIds", parentIds);
		map.put("id", id);
		controlDao.delControl(map);
	}
	@Override
	public List<TblControls> selectRootControl(Long appId) {
		return controlDao.selectRootControl(appId);
	}
	@Override
	public TblControls selectControlById(Long id) {
		TblControls controls =controlDao.selectControlById(id);
		if (controls.getControlLocationType()==3) {
			TblAttachment attachment = attachmentDao.selectFileById(controls.getControlImageAttachmentId());
			 String afterBase64 = (attachment==null || attachment.getFilePath()==null)?"":PictureTool.GetImageStr(targetFilePath+attachment.getFilePath());
			 controls.setPictrueBase(afterBase64);
		}
		return controls;
	}
	@Override
	public Long selectControlByName(Map<String, Object> map) {
		return controlDao.selectControlByName(map);
	}
	@Override
	public Long selectControlByCode(Long id) {
		return controlDao.selectControlByCode(id);
	}

	@Override
	public List<TblControls> selectControlWithChildById(Long id) {
		return controlDao.selectControlWithChildById(id);
	}

	@Override
	public List<TblControls> selectControlByParam(Map<String, Object> map) {
		List<TblControls> controls = controlDao.selectControlByParam(map); 
		return createControlTree(controls,null,null);
	}
	
	
	
	public List<TblControls> createControlTree(List<TblControls> list,List<Integer> typeList,Integer fg){
		List<TblControls> controlTree = new ArrayList<TblControls>();
		for(TblControls ctr:list) {
			
			if(fg != null &&typeList != null) {
				Integer  type = null;
				if(fg==1) {
					type  = ctr.getControlType();
				}else if(fg == 2) 
					type = ctr.getControlLocationType();
				if(type != null && !typeList.contains(type)) {
						JSONObject state = new JSONObject();
						state.put("disabled", true);
						ctr.setState(state);
				}
			}
			
				
			 if(ctr.getParentId() == null)
				 controlTree.add(ctr);
			 for(TblControls  ctr1:list) {
				 if(ctr1.getParentId() != null && ctr1.getParentId().equals(ctr.getId())) {
					 if(ctr.getChildren() == null)
						 ctr.setChildren(new ArrayList<TblControls>());
					 ctr.getChildren().add(ctr1);
				 }
			 }
		}
		return controlTree;
		
	}

	@Transactional
	@Override
	public void changeControlParent(Long id, Long parentId) throws Exception{
		
		TblControls control = controlDao.selectControlById(id);
		TblControls parentControl = controlDao.selectControlById(parentId);
		
		Map<String,Object> m1 = new HashMap<String,Object>();
		m1.put("controlName", control.getControlName());
		m1.put("parentId", parentId);
		m1.put("id", id);
		m1.put("appId", control.getAppId());
		Long count = this.selectControlByName(m1);
		if(count > 0) throw new Exception("存在相同名称的兄弟节点");
		
		String oldParentIds = control.getParentIds();
		String newParentIds = parentControl.getParentIds() == null?String.valueOf(parentId):(parentControl.getParentIds()+","+parentId);
		Integer len = oldParentIds == null?1:oldParentIds.length()+2;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("parentId", parentId);
		map.put("parentIds", newParentIds);
		map.put("id", id);
		controlDao.updateControlParent(map);
		
		Map<String,Object> m2 = new HashMap<String,Object>();
		m2.put("fatherNewParentIds", newParentIds);
		m2.put("len", len);
		m2.put("parentId", id);
		controlDao.updateChildControlParent(m2);
		
	}

	@Transactional
	@Override
	public void setControlToRoot(Long id) throws Exception{

		TblControls control = controlDao.selectControlById(id);
		
		Map<String,Object> m1 = new HashMap<String,Object>();
		m1.put("controlName", control.getControlName());
		m1.put("id", id);
		m1.put("appId", control.getAppId());
		Long count = this.selectControlByName(m1);
		if(count > 0) throw new Exception("存在相同名称的兄弟节点");
		
		String oldParentIds = control.getParentIds();
		Integer len = oldParentIds == null?1:oldParentIds.length()+2;
		controlDao.setControlToRoot(id);
		
		Map<String,Object> m2 = new HashMap<String,Object>();
		m2.put("len", len);
		m2.put("parentId", id);
		controlDao.updateChildControlParent(m2);
		
	
	}

	@Override
	public List<TblControls> selectControlByParamWithState(Map<String, Object> map) {
		List<TblControls> controls = controlDao.selectControlByParam(map); 
		String typeStr = map.get("typeStr") == null?null:map.get("typeStr").toString();
		String locateTypes = map.get("locateTypes") == null?null:map.get("locateTypes").toString();
		if(!StringUtils.isBlank(typeStr)) {
			List<Integer> typeList = new ArrayList<Integer>();
			for(String str:typeStr.split(",")) {
				typeList.add(Integer.valueOf(str));
			}
			return createControlTree(controls,typeList,1);
		}else if(!StringUtils.isBlank(locateTypes)) {
			List<Integer> typeList = new ArrayList<Integer>();
			for(String str:locateTypes.split(",")) {
				typeList.add(Integer.valueOf(str));
			}
			return createControlTree(controls,typeList,2);
		}
		return createControlTree(controls,null,null);
	}

	@Override
	public JSONObject selectControlName() {
		
		List<TblControls> list = controlDao.selectControlName();
		JSONObject json = new JSONObject();
		for(TblControls control:list) {
			json.put(control.getId().toString(), control.getControlName());
		}
		return json;
	}

}
